package cn.wolfcode.p2p.web.interceptor;

import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.web.util.RequiredLogin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            // 当前被请求的Controller的方法对象
            HandlerMethod hm = (HandlerMethod) handler;
            RequiredLogin requiredLogin = hm.getMethodAnnotation(RequiredLogin.class);
            if (requiredLogin != null && UserContext.getCurrentUser() == null) {
                // 此时有注解需要登录后访问,有注解且没登录
                response.sendRedirect("/login.html");
            }
        }
        return true;
    }
}
